<?php
//if more than 5 participants, start a poll and send emails;
//if less than 5, more than 0, close topic, delete from your day name list, add orders and send emails;
//if no one comes, close topic, delete from your day name list

//run at 00:05 on Tuesday, Thursday and Saturday
//topic_category_id still need to be changed!!

$now_weekday=date('w',time());

switch($now_weekday){
    case 2:
        $end_time=strtotime('Tuesday');
        break;
    case 4:
        $end_time=strtotime('Thursday');
        break;
    case 6:
        $end_time=strtotime('Saturday');
        break;
}

$time=$end_time;

$query=$this->db->query("SELECT name_id, name, forum_id, topic_id, topic_first_post_id FROM " . DB_PREFIX . "community_yourday WHERE used='0' AND being_used='1' AND being_polled='0' AND being_displayed='1' ORDER BY upcoming_date ASC LIMIT 0,1");

if($query->row){
    echo 'lock your day topic and start poll cron run';

    $participant_query=$this->db->query("SELECT * FROM " . DB_PREFIX . "community_yourday_participant WHERE name_id='" . $query->row['name_id'] . "'");

    //if more than 5 participants
    if(count($participant_query->rows)>5){
        //update as being polled
        $this->db->query("UPDATE " . DB_PREFIX . "community_yourday SET being_polled='1' WHERE name_id='" . $query->row['name_id'] . "'");

        //update topic as poll
        $this->db->query("UPDATE " . DB_PREFIX . "community_topics SET topic_polled='1', poll_title='Which 5 participants do you think deserve the freebie?', poll_start='" . $time . "', poll_length='" . (60*60*24) . "', poll_max_options='5' WHERE topic_id='" . (int)$query->row['topic_id'] . "'");

        //udpate post content
        $this->db->query("UPDATE " . DB_PREFIX . "community_posts SET post_text='" . $this->db->escape('Hi, community! We need you guys\' help. More than 5 participants were trying to claim the freebie. Please help vote on which 5 of them deserve it :)') . "' WHERE post_id='" . (int)$query->row['topic_first_post_id'] . "'");

        $poll_options=array();

        foreach($participant_query->rows as $participant){
            $poll_options[$participant['user_id']]=$participant['username'];
        }


        foreach($poll_options as $key => $poll_option){
            $this->db->query("INSERT INTO " . DB_PREFIX . "community_poll_options SET topic_id='" . (int)$query->row['topic_id'] . "', poll_option_id='" . (int)$key . "', poll_option_text='" . $this->db->escape($poll_option) . "', poll_option_total='0'");
        }

        //send email to participants
        $mail_num=0;

        foreach($participant_query->rows as $participant){
            if($mail_num==499){
                $subject =  'Emails sent to It\'s Your Day participants reach 499!';

                $message = 'Time is:' . date('Y-m-d H:i:s') . "\n";

                $mail = new Mail();
                $mail->protocol = $this->config->get('config_mail_protocol');
                $mail->parameter = $this->config->get('config_mail_parameter');
                $mail->hostname = $this->config->get('config_smtp_host');
                $mail->username = $this->config->get('config_smtp_username');
                $mail->password = $this->config->get('config_smtp_password');
                $mail->port = $this->config->get('config_smtp_port');
                $mail->timeout = $this->config->get('config_smtp_timeout');
                $mail->setTo('marcelwu@126.com');
                $mail->setFrom($this->config->get('config_community_email'));
                $mail->setSender($this->config->get('config_name') . "\40Community Emergency Team");
                $mail->setSubject(html_entity_decode($subject, ENT_QUOTES, 'UTF-8'));
                $mail->setText(html_entity_decode($message, ENT_QUOTES, 'UTF-8'));
                $mail->send();

                break;
            }
            echo 'email sent.';
            $subject =  'A Poll Launched On Which Five Participants Deserve The Freebie For' . ucwords($query->row['name']) . '\'s Day!';

            $message = "Oops! More than 5 participants were trying to claim the freebie for " . ucwords($query->row['name']) . "'s Day! We have to carry out a poll in the forum and let all other forum members vote on which five participants deserve it. The poll has kicked in and will end 24 hours later. You'd better now ask all your friends to vote for you, 'cause we believe you do deserve it :) Check it out at:\n";
            $message .= $this->url->link('community/viewtopic', 'fid=' . $query->row['forum_id'] . '&tid=' . $query->row['topic_id'], 'SSL') . "\n\n";
            $message .= "Cheers\n";
            $message .= $this->config->get('config_name') . "\40Community Manager Team";

            $mail = new Mail();
            $mail->protocol = $this->config->get('config_mail_protocol');
            $mail->parameter = $this->config->get('config_mail_parameter');
            $mail->hostname = $this->config->get('config_smtp_host');
            $mail->username = $this->config->get('config_smtp_username');
            $mail->password = $this->config->get('config_smtp_password');
            $mail->port = $this->config->get('config_smtp_port');
            $mail->timeout = $this->config->get('config_smtp_timeout');
            $mail->setTo($participant['user_email']);
            $mail->setFrom($this->config->get('config_community_email'));
            $mail->setSender($this->config->get('config_name') . "\40Community Manager Team");
            $mail->setSubject(html_entity_decode($subject, ENT_QUOTES, 'UTF-8'));
            $mail->setText(html_entity_decode($message, ENT_QUOTES, 'UTF-8'));
            $mail->send();

            $mail_num++;
            sleep(0.1);
        }

        //if participants less than 5 and more than 0
    }elseif($participant_query->rows && count($participant_query->rows)<=5){
        $this->db->query("UPDATE " . DB_PREFIX . "community_yourday SET used='1', being_displayed='0', being_used='0', being_polled='0' WHERE name_id='" . $query->row['name_id'] . "'");

        $this->db->query("UPDATE " . DB_PREFIX . "community_topics SET topic_status='1', topic_category_id='zzzz' WHERE topic_id='" . (int)$query->row['topic_id'] . "'");

        foreach($participant_query->rows as $participant){
            //get customer address
            $address_query = $this->db->query("SELECT DISTINCT * FROM " . DB_PREFIX . "address WHERE address_id = '" . (int)$participant['address_id'] . "' AND customer_id = '" . (int)$participant['customer_id'] . "'");

            $country_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "country` WHERE country_id = '" . (int)$address_query->row['country_id'] . "'");

            if ($country_query->num_rows) {
                $country = $country_query->row['name'];
                $iso_code_2 = $country_query->row['iso_code_2'];
                $iso_code_3 = $country_query->row['iso_code_3'];
                $address_format = $country_query->row['address_format'];
            } else {
                $country = '';
                $iso_code_2 = '';
                $iso_code_3 = '';
                $address_format = '';
            }

            $zone_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone` WHERE zone_id = '" . (int)$address_query->row['zone_id'] . "'");

            if ($zone_query->num_rows) {
                $zone = $zone_query->row['name'];
                $code = $zone_query->row['code'];
            } else {
                $zone = '';
                $code = '';
            }

            $address_data = array(
                'firstname'      => $address_query->row['firstname'],
                'lastname'       => $address_query->row['lastname'],
                'company'        => $address_query->row['company'],
                'address_1'      => $address_query->row['address_1'],
                'address_2'      => $address_query->row['address_2'],
                'postcode'       => $address_query->row['postcode'],
                'city'           => $address_query->row['city'],
                'zone_id'        => $address_query->row['zone_id'],
                'zone'           => $zone,
                'zone_code'      => $code,
                'country_id'     => $address_query->row['country_id'],
                'country'        => $country,
                'iso_code_2'     => $iso_code_2,
                'iso_code_3'     => $iso_code_3,
                'address_format' => $address_format
            );

            //add order
            $this->db->query("INSERT INTO `" . DB_PREFIX . "order` SET invoice_prefix = '', store_id = '0', store_name = 'Micbus.com', store_url = '" . $this->db->escape('http://www.micbus.com') . "', customer_id = '" . (int)$participant['customer_id'] . "', customer_group_id = '" . (int)$participant['customer_group_id'] . "', firstname = '" . $this->db->escape($address_data['firstname']) . "', lastname = '" . $this->db->escape($address_data['lastname']) . "', email = '" . $this->db->escape($participant['user_email']) . "', telephone = '', fax = '', payment_firstname = '" . $this->db->escape($address_data['firstname']) . "', payment_lastname = '" . $this->db->escape($address_data['lastname']) . "', payment_company = '" . $this->db->escape($address_data['company']) . "', payment_address_1 = '" . $this->db->escape($address_data['address_1']) . "', payment_address_2 = '" . $this->db->escape($address_data['address_2']) . "', payment_city = '" . $this->db->escape($address_data['city']) . "', payment_postcode = '" . $this->db->escape($address_data['postcode']) . "', payment_country = '" . $this->db->escape($address_data['country']) . "', payment_country_id = '" . (int)$address_data['country_id'] . "', payment_zone = '" . $this->db->escape($address_data['zone']) . "', payment_zone_id = '" . (int)$address_data['zone_id'] . "', payment_address_format = '', payment_code = '" . $this->db->escape('free_checkout') . "', payment_method = '" . $this->db->escape('Free Checkout') . "', language_id = '1', currency_id = '2', currency_code = 'USD', comment='" . $this->db->escape(ucwords($query->row['name'])) . " Day', currency_value = '1', order_status_id='1', date_added = NOW(), date_modified = NOW()");

            $order_id = $this->db->getLastId();

            $this->db->query("INSERT INTO " . DB_PREFIX . "order_product SET order_id = '" . (int)$order_id . "', product_id = '613', name = '" . $this->db->escape('$20 Worth of Free Sample - (A TF Card Needed To Player Music) TF / Micro SD Card Reader Clip MP3 Player - 5 Samples Per Day') . "', model = '" . $this->db->escape('F0001') . "', quantity = '1', price = ' 0.0000', total = '0', tax = '0', reward = '0'");


            $this->db->query("INSERT INTO " . DB_PREFIX . "order_total SET order_id = '" . (int)$order_id . "', code = '" . $this->db->escape('sub_total') . "', title = '" . $this->db->escape('Sub-Total') . "', text = '" . $this->db->escape('$0.00') . "', `value` = '0', sort_order = '1'");

            $this->db->query("INSERT INTO " . DB_PREFIX . "order_total SET order_id = '" . (int)$order_id . "', code = '" . $this->db->escape('total') . "', title = '" . $this->db->escape('Total') . "', text = '" . $this->db->escape('$0.00') . "', `value` = '0', sort_order = '2'");

            //send emails
            $subject = 'Congratulations! You Have Won The Freebie For' . ucwords($query->row['name']) . '\'s Day!';

            $message = "Since less than 5 participants were trying to claim the freebie for\40" . ucwords($query->row['name']) . "'s Day, you win the freebie now! An order for the freebie has been added into your account and you can check it out at:\n";
            $message .= $this->url->link('account/order') . "\n\n";
            $message .= "Cheers\n";
            $message .= $this->config->get('config_name') . "\40Community Manager Team";

            $mail = new Mail();
            $mail->protocol = $this->config->get('config_mail_protocol');
            $mail->parameter = $this->config->get('config_mail_parameter');
            $mail->hostname = $this->config->get('config_smtp_host');
            $mail->username = $this->config->get('config_smtp_username');
            $mail->password = $this->config->get('config_smtp_password');
            $mail->port = $this->config->get('config_smtp_port');
            $mail->timeout = $this->config->get('config_smtp_timeout');
            $mail->setTo($participant['user_email']);
            $mail->setFrom($this->config->get('config_community_email'));
            $mail->setSender($this->config->get('config_name') . "\40Community Manager Team");
            $mail->setSubject(html_entity_decode($subject, ENT_QUOTES, 'UTF-8'));
            $mail->setText(html_entity_decode($message, ENT_QUOTES, 'UTF-8'));
            $mail->send();

            sleep(0.1);
        }

        //no one wins
    }else{
        $this->db->query("UPDATE " . DB_PREFIX . "community_yourday SET used='1', being_displayed='0', being_used='0', being_polled='0' WHERE name_id='" . $query->row['name_id'] . "'");

        $this->db->query("UPDATE " . DB_PREFIX . "community_topics SET topic_status='1', topic_category_id='zzzz' WHERE topic_id='" . (int)$query->row['topic_id'] . "'");
    }

    //clear sql cache
    $this->sql_cache->delete('viewtopic.posts.' . md5($query->row['topic_id']));
    $this->sql_cache->delete('viewforum.topics.' . md5($query->row['forum_id']));
}

//clear your name cache
$this->sql_cache->delete('community.upcomingnames');
?>